import { EResType } from "../../../Script/Common/Enum";
import { GlobalData, ILotteryGrade } from "../../../Script/Common/GlobalData";
import { IFlyResData } from "../../../Script/Interface/IMessage";
import { SceneGame } from "../../../Script/SceneGame";
import GameUtil from "../../../Script/Util/GameUtil";
import { LoadUtil } from "../../../Script/Util/LoadUtil";
import Eraser from "./Eraser";
import LotteryUI from "./LotteryUI";

const MAX_ANIMAL: number = 9;

interface IRewardData {
    /** iconid */
    id: number;
    /** 奖励金额 */
    value: number;
    // /** 倍数 */
    // ratio: number;
    /** 奖励索引 */
    pos?: number[];
}

const { ccclass, property } = cc._decorator;

@ccclass
export default class Animal extends Eraser {

    @property({ type: cc.Node, tooltip: "刮刮乐对照点" })
    protected compare: cc.Node = null;
    
    /** 中奖对照数据 */
    private reward: IRewardData = null;

    public restart() {
        super.restart();

        const p = Math.random() * 100;
        if (p <= this.data.p) { // 中奖
            // 小额最多中奖4次
            const num = Math.ceil(Math.random() * this.grade.max);
            const arr = this.getIndexArr();
            const indexs = GameUtil.getRandomElement(arr, num);
            this.refreshItems(indexs, this.grade);

            console.log("中奖--", this.grade.id, '---', num);
        } else {
            this.refreshItems([], this.grade);

            console.log("未中奖~");
        }
    }

    private refreshItems(indexs: number[], grade: ILotteryGrade) {
        // 刷新奖励
        const iconId = this.random(MAX_ANIMAL);
        const value = this.random(grade.values);
        this.reward = { id: iconId, value: value };
        this.refreshItem(this.compare, this.reward);

        const arr = this.excludeWinIcon();
        this.items.children.forEach((o, i) => {
            this.positions.push(cc.v2(o.x, o.y));
            const id = this.random(arr);
            const value = this.random(this.totalArr);
            this.refreshItem(o, { id, value });
        });
        this.positionProgress = new Array(this.positions.length);

        // 重刷中奖展示
        for (let k = 0; k < indexs.length; k++) {
            const index = indexs[k];
            const node = this.items.children[index];
            this.refreshItem(node, this.reward);
        }
        // 中奖位置
        this.reward.pos = indexs;
    }

    /** 兑奖 */
    protected async checkReward() {
        try {
            super.checkReward();
            const len = this.reward.pos.length;
            if (len > 0) {
                for (let i = 0; i < len; i++) {
                    const index = this.reward.pos[i];
                    const data = SceneGame.instance.getFlyResData();
                    const flyData: IFlyResData = {
                        resType: EResType.Money,
                        parent: data.flyNode,
                        from: this.items.children[index],
                        to: data.money,
                        value: this.reward.value,
                        flyTimes: 10,
                        maxWidth: 60,
                        maxHeight: 60,
                    }
                    GameUtil.instance.flyResIcon(flyData);
                    console.log(`动物id:${this.reward.id}  中奖金额:${this.reward.value}  位置: ${index}`);
                    await GameUtil.sleep(200);
                }
            } else {
                console.log("未中奖~");
            }
        } catch (error) {
            console.log(error);
        }
    }

    private getIndexArr() {
        const temp: number[] = [];
        const len = this.items.children.length;
        for (let i = 0; i < len; i++) {
            temp.push(i);
        }
        return temp;
    }

    private excludeWinIcon() {
        const ex = [];
        for (let i = 0; i < MAX_ANIMAL; i++) {
            if (i !== this.reward.id) {
                ex.push(i);
            }
        }
        return ex;
    }

    private refreshItem(node: cc.Node, data: IRewardData) {
        try {
            const icon = cc.find("icon", node).getComponent(cc.Sprite);
            const num = cc.find("layout/num", node).getComponent(cc.Label);
            num.string = `${GameUtil.changeUnit(data.value, 0)}`;
            LoadUtil.instance.setSpriteFrame(icon, EResType.LotteryAnimal, data.id);
        } catch {
            console.log(node, data);
        }
    }
}